package com.xiaoxin.common.dynamicds.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@ConditionalOnClass(DynamicRoutingDataSource.class)
@AutoConfigureAfter(DynamicDataSourceAutoConfiguration.class)
@ConditionalOnProperty(name = "dynamic.datasource.enabled", havingValue = "true", matchIfMissing = true)
public class DynamicDataSourceAutoConfig {

    @Bean
    @ConditionalOnBean(DataSource.class)
    public DataSourceRegistrar dataSourceRegistrar(DataSource dataSource, ConfigurableListableBeanFactory beanFactory) {
        DynamicRoutingDataSource dynamicDataSource = (DynamicRoutingDataSource) dataSource;
        Map<String, DataSource> dataSourceMap = dynamicDataSource.getDataSources();
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            String dataSourceName = entry.getKey();
            DataSource ds = entry.getValue();
            beanFactory.registerSingleton(dataSourceName, ds);
            System.out.println("注册数据源：" + dataSourceName);
        }
        return new DataSourceRegistrar();
    }

}

